package com.educatioin.manage.web;

import com.educatioin.commons.util.AjaxResult;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;

/**
 * Created by caizh on 18-3-5.
 */
@Controller
@RequestMapping("/file")
public class FileUploadController {

    private static Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    //格式
    private final static String picAllowSuffix = "png,jpg,gif";

    private String tmpPath = System.getProperty("user.home") + File.separator + "pic";

    //大小
    private final static int picAllowSize = 10 * 1024 * 1024;

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    @RequestMapping("/download/{file:.+}")
    public void download(@PathVariable String file, HttpServletResponse response) throws IOException {
        File img = new File(tmpPath + File.separator + file);
        try (OutputStream toClient = response.getOutputStream()) {
            if(img.exists()){
                FileInputStream is = new FileInputStream(img);
                int i = is.available(); // 得到文件大小
                byte data[] = new byte[i];
                is.read(data); // 读数据
                is.close();
                response.setContentType("image/*");
                toClient.write(data); // 输出数据
                toClient.flush();
                toClient.close();
            }
        }
    }

    @RequestMapping(value = "uploadPic")
    @ResponseBody
    public AjaxResult uploadPic(@RequestParam(value = "file", required = false) MultipartFile file,
                                HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("utf-8");
        AjaxResult result = new AjaxResult();
        logger.info("上传图片开始");
        File tmpFile = null;
        try {
            //获取文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            if (StringUtils.isNotBlank(picAllowSuffix)) {
                if (!picAllowSuffix.contains(suffix.toLowerCase())){
                    result.setCode(AjaxResult.ERROR_CODE);
                    result.setMsg("请上传允许格式的图片");
                    return result;
                }
            }
            long size = file.getSize();
            if(size > picAllowSize){
                result.setCode(AjaxResult.ERROR_CODE);
                result.setMsg("超过上传图片大小限制");
                return result;
            }
            String fileName = LocalDateTime.now().format(dateTimeFormatter) + UUID.randomUUID().hashCode()+"."+suffix;
            File baseFile = new File(tmpPath);
            tmpFile = new File(baseFile, fileName);
            if (!baseFile.exists()) {
                baseFile.mkdirs();
            }
            //保存临时文件
            file.transferTo(tmpFile);

            result.setCode(AjaxResult.SUCCESS_CODE);
            Map<String, String> data = Maps.newHashMap();
            data.put("src", request.getContextPath() + "/file/download/" + tmpFile.getName());
            data.put("title", tmpFile.getName());
            result.setData(data);
            logger.info("上传图片结束");
        } catch (Exception e) {
            logger.error("上传图片出错",e);
            result.setCode(AjaxResult.ERROR_CODE);
            result.setMsg("上传失败: " +e.getMessage());
        }
        return result;
    }
}
